/**
 * @class Zuosa
 * @fileOverview 做啥微博控制器
 * @extends yijs.air.Controller
 */ 
var Zuosa = function(user){
	this.config			  = yijs.config.zuosa;
	this.ModelOption	  = new Option();
	this.ModelTemp  	  = new Temp();
	this.ModelMsg    	  = new Msg();
	this.type 			  = Zuosa.TYPE[1];
	this.lang 			  = yijs.lang.zuosa;
	this.viewPath         = getViewPath(yijs.config.viewName.zuosa);
	this.itemsViewPath    = getViewPath(yijs.config.viewName.zuosaItems);
	this.user             = user;
	this.userField        = this.config.userField;
	this.ajaxApplyTo      = ".MAIN";
	this.id               = "ZUOSA";
	this.contentContainer = "MAIN_CONTENT";
	this.$content         = null;
	this.view();
}
/**服务器端返回的数据类型*/
Zuosa.TYPE = ["json","xml","rss","atom"];

Zuosa.API = "http://api.zuosa.com/";
Zuosa.APIURI = ['search','statuses','users','friendships','direct_messages','account','tag','register','help','favorites','blocks'];
Zuosa.ACTION = {
		/**搜索*/
		search : "search",
		/**显示大家在做啥*/
		publicMsg : "public_timeline",
		/**显示用户在做啥*/
		userMsg : "user_timeline",
		/**显示用户和好友在做啥*/
		friendsMsg : "friends_timeline",
		/**获取一条指定的消息*/
		getMsg : "show",
		/**发布一条新消息*/
		updateMsg : "update",
		/**删除一条消息*/
		delMsg : "destroy",
		/**获取一条指定的消息*/
		getMentions : "mentions",
		/**用户验证*/
		verify : "verify_credentials",
		user : "show"		
}
/**
 * 读取并解析模板
 */
Zuosa.prototype.view = function(){
	var _that = this;
	var langsXml = getLangXml(this.lang);
	yijs.air.view(langsXml,{url:this.viewPath},"body",function(xml,xsl){_that.viewHandler(xml,xsl)});
	
}
/**
 * 解析完模板后触发的事件
 * @param {Object} xml
 * @param {Object} xsl
 */
Zuosa.prototype.viewHandler = function(xml,xsl){
	var _that = this;
	this.$content = $("#"+this.id).children("#"+this.contentContainer); 
	this.setAjax();	
	yijs.hover("#face","face_hover");
	yijs.hover("#LEFT_NAV > li","LEFT_NAV_item_hover");
	this.setNavHeaderSlide();
	this.setUser();	
	this.getMyMsg();
	
	$("#NAV_MSG").click(function(){
		_that.removeItems(function(){
			_that.getMyMsg();
		});
		
	})
	
	$("#USER").click(function(){
		_that.setUser();	
	})
	
}
/**
 * 获取我的信息
 */
Zuosa.prototype.getMyMsg = function(){
	var _that = this;
	var _name = this.user.name;
	var _api = this.getUrl(Zuosa.APIURI[1],Zuosa.ACTION.userMsg);
	var _testApi = "App:/json/user.xml"
	$.ajax({
	    url : _testApi,
	    method : 'GET',
		dataType : "xml",
		success : function(data){
			_that.insertDbMsg(data,function(){
				_that.setMyMsg();
			});
		}
	});		
	//yijs.air.view({url:_api,data:{id:_name}},{url:this.itemsViewPath},"#MAIN_CONTENT",function(xml,xsl){_that.showMsgHandler()});	
}
/**
 * 将消息插入到xml
 * @param {Object} data xml
 * @param {function} fnCallBack 插入完成后回调函数
 */
Zuosa.prototype.insertDbMsg = function(data,fnCallBack){
	var _controller = this.user.controller;
	var _action = Zuosa.ACTION.userMsg;
	//最后获取时间戳的key名
	var _lastGetTimerField = _controller + "_" + _action + "last_timer";
	var $status = $(data).find("status");
	var _size = $status.size();
	if(_size > 0){
		for(var i = _size-1 ;i >=0 ; i--){
				var _user = $status.eq(i).children("user");
				//将时间转化为时间戳
		        var date = new Date($status.eq(i).children("created_at").text());
				var _created_at = date.getTime();	
				//获取最后获取时间戳
				var _lastGetTimer = this.ModelTemp.get(_lastGetTimerField);
				//大于最后获取时间戳写入到数据库
				if(_created_at > _lastGetTimer){
					var _data = {controller             : _controller,action :_action,
					             msg_id                 : $status.eq(i).children("id").text(),
								 created_at             : _created_at,
								 text                   : $status.eq(i).children("text").text(),
								 source                 : $status.eq(i).children("source").text(),
								 user_id                : _user.children("id").text(),
								 user_name              : _user.children("name").text(),
								 user_screen_name       : _user.children("screen_name").text(),
								 user_location          : _user.children("location").text(),
								 user_description       : _user.children("description").text(),
								 user_profile_image_url : _user.children("profile_image_url").text(),
								 user_url               : _user.children("url").text(),
								 user_protected         : _user.children("protected").text()
					}
					this.ModelMsg.insert(_data);							
				}
				//更新最后获取时间戳
				i == 0 && this.ModelTemp.update(_lastGetTimerField,_created_at);		 			
		}
		if(fnCallBack) fnCallBack.call(this);
	}
	return true;			 
}
/**
 * 从数据库提取我的消息并予以显示
 */
Zuosa.prototype.setMyMsg = function(){
	var _controller = this.user.controller;
	var _action = Zuosa.ACTION.userMsg;	
	var result = this.ModelMsg.getAssignMsgs(_controller,_action);
}
/**
 * 显示信息
 */
Zuosa.prototype.showMsgHandler = function(){
			//给奇数li加上样式
		    var $liOdd = this.$content.find("li:odd");
			$liOdd.addClass("yijs_zuosa_msg_item_odd");
			
			var $li = this.$content.find("li"); 
			var time = this.$content.find(".yijs_zuosa_msg_item_created");
			time.html(function(i,t){;
                var date = new Date(t);
				var time = date.getTime();			
				return formatTime(t);
			}) 
			var len = $li.size();
			_animate(0);
			/**
			 * li显示动画
			 * @param {Object} eq
			 */	
			function _animate(eq){
				$li.eq(eq).fadeIn("fast",function(){
					if(eq < len-1){
						  eq ++;
						  _animate(eq);						
					}
				})
			}		
}
/**
 * 删除内容
 */
Zuosa.prototype.removeItems = function(fnCallBack){
	var $li = this.$content.find("li"); 
	var len = $li.size();
	if(len > 0){
			_animate(len-1);
			/**
			 * li隐藏动画
			 * @param {Object} eq
			 */	
			function _animate(eq){
				$li.eq(eq).fadeOut("fast",function(){
					eq > 0 && eq -- && $(this).remove() && _animate(eq);						
					if(fnCallBack && eq == 0)  fnCallBack.call(this);
				})
			}
	}else{
		if(fnCallBack )  fnCallBack.call(this);
	}
}
Zuosa.prototype.setNavHeaderSlide = function(){
	var $slide = $("#NAV_HEADER_SLIDE");
	var ulWidth = $slide.parent().width();
	var $ul = $slide.children("ul");
	$ul.width(ulWidth);
	$slide.width(ulWidth * $ul.size());
	
	var $li = $("#LEFT_NAV > li");
	$li.mouseover(function(){
		var index = $li.index($(this));
		var marginLeft = index == 0 && 0 || "-" + index * ulWidth;
		$slide.stop().animate({"marginLeft": marginLeft},"fast");
	});
}
Zuosa.prototype.verify = function(Authorization,success){
		var url = Zuosa.API+Zuosa.APIURI[5]+"/"+Zuosa.ACTION["verify"]+"."+this.type;
		$.ajax({
		    url : url,
		    method : 'GET',
			dataType : "xml",
		    beforeSend : function(req) {
		        req.setRequestHeader('Authorization', Authorization);
		    },
			success : function(data){
				if(success) success.call(this,data);
			}
		});		
}
/**
 * 获取用户信息,并予以显示
 */
Zuosa.prototype.setUser = function(){
	var _that = this;
	var url = this.getUrl(Zuosa.APIURI[2],Zuosa.ACTION["user"]);
		$.ajax({
		    url : url,
		    method : 'GET',
			dataType : "text",
			data : {"id" : "36ria"},
			success : function(data){_setUserHandler(data);}
		});
	
	/**
	 * @private
	 * 处理ajax返回的数据
	 * @param {Object} data xml数据
	 */	
	function _setUserHandler(data){
			   
				var user = {};
				user.id = $(data).find(_that.userField.id).text();
				user.name = $(data).find(_that.userField.name).text();
				user.face = $(data).find(_that.userField.face).text();
				user.createdTimer = $(data).find(_that.userField.createdTimer).text();
				user.position = $(data).find(_that.userField.position).text();
				user.description = $(data).find(_that.userField.description).text();
				$("#USERNAME").text(user.name);
				$("#USERNAME").data(user);
				$("#FACE").children("img").attr("src",user.face);		
	}		
}
/**
 * 设置ajax事件
 */
Zuosa.prototype.setAjax = function(){
	var _that = this;
	$(_that.ajaxApplyTo).ajaxSend(function(e,xhr, settings){
		preLoad.show();
		var name = _that.user.name;
		var password = _that.user.password;
		var Authorization = "Basic " + Base64.encode(name+":"+password);
		xhr.setRequestHeader('Authorization', Authorization);
	})
	$(_that.ajaxApplyTo).ajaxSuccess(function(){
		
	})
	$(_that.ajaxApplyTo).ajaxComplete(function(){
		preLoad.hide();
	})
}
Zuosa.prototype.getUrl = function(apiUri,action){
	return Zuosa.API+apiUri+"/"+action+"."+this.type;
}

